package cn.jdemo.unsafe.offset;

import sun.misc.Unsafe;

import java.lang.reflect.Field;

/**
 * @see Unsafe#staticFieldOffset(Field) 静态变量相对于类内存地址的偏移量
 * @see Unsafe#objectFieldOffset(Field) 非静态变量相对于实例化对象的偏移量
 * @see Unsafe#fieldOffset(Field) 过期，不使用
 * 
 * @date 2021/1/15
 */
public class Demo01 {
    /**
     * 输出内容:
     * 静态变量相对于类内存地址的偏移量:
     * 104
     * 非静态变量相对于实例化对象的偏移量:
     * 12
     */
    public static void main(String[] args) {
        System.out.println("静态变量相对于类内存地址的偏移量:");
        test01();
        System.out.println("非静态变量相对于实例化对象的偏移量:");
        test02();
    }

    public static void test01() {
        Unsafe theUnasfe = cn.jdemo.unsafe.theUnsafe.AllInOne.getTheUnasfe();
        Class<A> aClass = A.class;
        try {
            long intVal1 = theUnasfe.staticFieldOffset(aClass.getDeclaredField("intVal1"));
            System.out.println(intVal1);// 104
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }
    }

    public static void test02() {
        Unsafe theUnasfe = cn.jdemo.unsafe.theUnsafe.AllInOne.getTheUnasfe();
        A a = new A();
        Class<? extends A> aClass = a.getClass();
        try {
            long intVal2 = theUnasfe.objectFieldOffset(aClass.getDeclaredField("intVal2"));
            System.out.println(intVal2);
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }
    }
    static class A{
        static int intVal1=0;
        int intVal2=0;
    }
}
